package core

import (
	"KumquatDrivesServices/conf"
	"KumquatDrivesServices/global"
	"gorm.io/driver/postgres"
	"strings"
	"time"

	"github.com/sirupsen/logrus"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/plugin/dbresolver"
)

func selectDatabase(Config conf.DB) gorm.Dialector {
	dbSource := strings.ToLower(Config.Source)
	switch dbSource {
	case "mysql":
		return mysql.Open(Config.DSN())
	default:
		return postgres.Open(Config.DSN())
	}
}
func InitDB() *gorm.DB {
	gdc := global.Config.DB
	gdc1 := global.Config.DB1
	logrus.Info("数据库连接中...")
	db, err := gorm.Open(selectDatabase(gdc), &gorm.Config{
		DisableForeignKeyConstraintWhenMigrating: false,
	})
	if err != nil {
		logrus.Fatalf("数据库连接失败:%v", err)
	}
	sqlDB, _ := db.DB()
	sqlDB.SetMaxIdleConns(10)
	sqlDB.SetMaxOpenConns(100)
	sqlDB.SetConnMaxLifetime(time.Hour)
	if !gdc1.Empty() {
		//如果读写库不为空，则配置读写分离
		err = db.Use(dbresolver.Register(dbresolver.Config{
			Sources:  []gorm.Dialector{selectDatabase(gdc1)}, //写
			Replicas: []gorm.Dialector{selectDatabase(gdc)},  //读
			Policy:   dbresolver.RandomPolicy{},
		}))
		if err != nil {
			logrus.Fatalf("读写分离配置失败:%v", err)
		}
	}
	logrus.Info("数据库连接成功")
	return db
}
